package eo.builder.util;

public abstract class AbstractClassLoadingIterationStep implements
        IterationStep<String> {

    private final ClassLoader classLoader;

    /**
     * 
     * @param classLoader
     *            the {@link ClassLoader} to load the class. Must have the
     *            visiting URL as a classpath entry.
     */
    public AbstractClassLoadingIterationStep(ClassLoader classLoader) {
        super();
        this.classLoader = classLoader;
    }

    public boolean nextIteration(String e) {
        if (e.endsWith(".class")) {
            String clName = e.substring(0, e.lastIndexOf(".class")).replaceAll(
                    "[/]", ".");
            try {
                Class<?> cl = Class.forName(clName, false, this.classLoader);
                return this.classFound(cl);
            } catch (ClassNotFoundException e1) {
                this.classNotFound(clName);
            }
        }
        return true;
    }

    /**
     * Reacts to a class. If it returns false, iteration will stop.
     * 
     * @param clazz
     *            the {@link Class}
     * @return boolean
     */
    protected abstract boolean classFound(Class<?> clazz);

    /**
     * Reacts to a class not found exception.
     * 
     * @param className
     *            the class name
     */
    protected void classNotFound(String className) {
    }

}
